﻿using System;
using System.Collections.Generic;

namespace DataBroker.Dao
{
    ///<summary>
    /// Extension class to support client side manipulation
    ///</summary>
    public static class Extension
    {
        ///<summary>
        /// Sort entity instances
        ///</summary>
        ///<param name="coll"></param>
        ///<param name="converter"></param>
        ///<param name="comparison"></param>
        ///<typeparam name="Entity"></typeparam>
        ///<typeparam name="TSortBy"></typeparam>
        public static void SortBy<Entity, TSortBy>(
            this List<Entity> coll,
            Converter<Entity, TSortBy> converter,
            Comparison<TSortBy> comparison)
        {
            var temp = coll.ConvertAll(
                el => new { Key = converter(el), Value = el });
            temp.Sort((a, b) => comparison(a.Key, b.Key));
            for (int i = 0; i < coll.Count; i++)
                coll[i] = temp[i].Value;
        }
        ///<summary>
        ///</summary>
        ///<param name="coll"></param>
        ///<param name="converter"></param>
        ///<typeparam name="Entity"></typeparam>
        ///<typeparam name="TSortBy"></typeparam>
        public static void SortBy<Entity, TSortBy>(
            this List<Entity> coll,
            Converter<Entity, TSortBy> converter)
            where TSortBy : IComparable
        {
            SortBy(coll, converter, (a, b) => a.CompareTo(b));
        }
    }
}